package org.jeecg.modules.basicShelf.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.basicCompartment.entity.BasicCompartment;
import org.jeecg.modules.basicCompartment.service.IBasicCompartmentService;
import org.jeecg.modules.basicShelf.entity.BasicShelf;
import org.jeecg.modules.basicShelf.service.IBasicShelfService;
import org.jeecg.modules.basicShelfType.entity.BasicShelfType;
import org.jeecg.modules.basicShelfType.service.IBasicShelfTypeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Description: 货架表
 * @Author: jeecg-boot
 * @Date: 2023-11-01
 * @Version: V1.0
 */
@Api(tags = "货架表")
@RestController
@RequestMapping("/basicShelf/basicShelf")
@Slf4j
public class BasicShelfController extends JeecgController<BasicShelf, IBasicShelfService> {
    @Autowired
    private IBasicShelfService basicShelfService;
    @Autowired
    private IBasicCompartmentService compartmentService;
    @Autowired
    private IBasicShelfTypeService basicShelfTypeService;
    @Autowired
    private IBasicCompartmentService basicCompartmentService;

    /**
     * 分页列表查询
     *
     * @param basicShelf
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "货架表-分页列表查询")
    @ApiOperation(value = "货架表-分页列表查询", notes = "货架表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(BasicShelf basicShelf,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        QueryWrapper<BasicShelf> queryWrapper = QueryGenerator.initQueryWrapper(basicShelf, req.getParameterMap());
        queryWrapper.likeRight("sys_org_code", user.getOrgCode());
        Page<BasicShelf> page = new Page<BasicShelf>(pageNo, pageSize);
        IPage<BasicShelf> pageList = basicShelfService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    @GetMapping("/getAll")
    public Result<?> getAll() {
        List<BasicShelf> list = basicShelfService.list();
        return Result.OK(list);
    }

    /**
     * 添加
     *
     * @param basicShelf
     * @return
     */
    @AutoLog(value = "货架表-添加")
    @ApiOperation(value = "货架表-添加", notes = "货架表-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody BasicShelf basicShelf) {
        basicShelf.setShelfCode(basicShelf.getShelfTypeCode() + basicShelf.getWarehouseCode() + basicShelf.getShelfCode());
        LambdaQueryWrapper<BasicShelf> shelfLqw = Wrappers.lambdaQuery(BasicShelf.class);
        shelfLqw.eq(BasicShelf::getShelfCode, basicShelf.getShelfCode());
        BasicShelf shelf = basicShelfService.getOne(shelfLqw);
        if (Objects.isNull(shelf)) {
            basicShelfService.save(basicShelf);
        } else {
            return Result.error("货架编码已存在！");
        }
        //同步生成对应的货格数据
        LambdaQueryWrapper<BasicShelfType> lqw = Wrappers.lambdaQuery(BasicShelfType.class);
        lqw.eq(BasicShelfType::getShelfCode, basicShelf.getShelfTypeCode());
        BasicShelfType shelfType = basicShelfTypeService.getOne(lqw);
        Integer plie = shelfType.getPlie();//层数
        Integer colums = shelfType.getColums();//每层格数
        List<BasicCompartment> list = new ArrayList<>();
        int loopCount = plie * colums;
        ;
        for (int i = 0; i < loopCount; i++) {
            int layer = i / colums + 1;  // 计算当前层
            char position = (char) ('a' + i % colums);  // 计算当前位置，转换为字母
            String name = basicShelf.getShelfCode() + layer + "" + position;  // 组合名称，例如1a, 1b, 1c...
            BasicCompartment compartment = new BasicCompartment();
            // 判断当前循环是否大于 plie * colums
            if (i >= plie * colums) {
                // F面
                name = basicShelf.getShelfCode() + "B" + (layer - plie) + "" + position;
                compartment.setCompartmentCode(name);
//                compartment.setIsTwoSided("B");
            } else {
                // B面
                compartment.setCompartmentCode(name);
//                compartment.setIsTwoSided("F");
            }
            compartment.setShelfCode(basicShelf.getShelfCode());
            compartment.setCompartmentUtilization(0.00);
            list.add(compartment);
        }
        compartmentService.saveBatch(list);//添加货格数据
        return Result.OK("添加成功！");
    }

    /**
     * 添加
     *
     * @param basicShelf
     * @return
     */
    @AutoLog(value = "货架表-添加")
    @ApiOperation(value = "货架表-添加", notes = "货架表-添加")
    @PostMapping(value = "/addShelf")
    public Result<?> addShelf(@RequestBody BasicShelf basicShelf) {
        //同步生成对应的货格数据
        LambdaQueryWrapper<BasicShelfType> shelfTypeLqw = Wrappers.lambdaQuery(BasicShelfType.class);
        shelfTypeLqw.eq(BasicShelfType::getShelfCode, basicShelf.getShelfTypeCode());
        BasicShelfType shelfType = basicShelfTypeService.getOne(shelfTypeLqw);
        Integer plie = shelfType.getPlie();//层数
        // 1.0 获取待生成的货架数量，添加货架信息
        String[] split = basicShelf.getShelfCode().split("~");
        int startShelfCode = Integer.parseInt(split[0]);//起始编码
        int endShelfCode = Integer.parseInt(split[1]);//结束编码
        if (startShelfCode >= endShelfCode) {
            return Result.error("货架结束编码必须大于货架起始编码！");
        }
        // 1.1 循环判断待生成的货架是否已存在，添加货架
        List<BasicShelf> basicShelves = new ArrayList<>();
        List<BasicCompartment> compartments = new ArrayList<>();
        String shelfTypeCode = basicShelf.getShelfTypeCode();
        for (int i = startShelfCode; i <= endShelfCode; i++) {
            String shelfCode = shelfTypeCode + (i < 10 ? "0" + i : i);
            LambdaQueryWrapper<BasicShelf> lqw = Wrappers.lambdaQuery(BasicShelf.class);
            lqw.eq(BasicShelf::getShelfCode, shelfCode);
            BasicShelf shelf = basicShelfService.getOne(lqw);
            if (!Objects.isNull(shelf)) {
                return Result.error("添加的货架中有已存在的货架，请确认后重新提交！");
            }
            // 1.2 添加货架
            BasicShelf basicShelf1 = new BasicShelf();
            BeanUtils.copyProperties(basicShelf, basicShelf1);
            basicShelf1.setShelfCode(shelfCode);
            basicShelves.add(basicShelf1);

            // 1.3 添加货格
            for (int j = 1; j <= plie; j++) {
                String compartmentCode = shelfCode + (j < 10 ? "-0" + j : "-" + j);
                BasicCompartment compartment = new BasicCompartment();
                compartment.setShelfCode(shelfCode);
                compartment.setCompartmentCode(compartmentCode);
                compartments.add(compartment);
            }
        }
        basicShelfService.saveBatch(basicShelves);
        compartmentService.saveBatch(compartments);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param basicShelf
     * @return
     */
    @AutoLog(value = "货架表-编辑")
    @ApiOperation(value = "货架表-编辑", notes = "货架表-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody BasicShelf basicShelf) {
        basicShelfService.updateById(basicShelf);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "货架表-通过id删除")
    @ApiOperation(value = "货架表-通过id删除", notes = "货架表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        BasicShelf basicShelf = basicShelfService.getById(id);
        basicShelfService.removeById(id);
        LambdaQueryWrapper<BasicCompartment> lqw = Wrappers.lambdaQuery(BasicCompartment.class);
        lqw.eq(BasicCompartment::getShelfCode, basicShelf.getShelfCode());
        basicCompartmentService.remove(lqw);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "货架表-批量删除")
    @ApiOperation(value = "货架表-批量删除", notes = "货架表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        List<BasicShelf> shelfList = basicShelfService.listByIds(Arrays.asList(ids.split(",")));
        this.basicShelfService.removeByIds(Arrays.asList(ids.split(",")));
        List<String> shelfCodeList = shelfList.stream().map(item -> {
            return item.getShelfCode();
        }).collect(Collectors.toList());
        LambdaQueryWrapper<BasicCompartment> lqw = Wrappers.lambdaQuery(BasicCompartment.class);
        lqw.in(BasicCompartment::getShelfCode, shelfCodeList);
        basicCompartmentService.remove(lqw);
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "货架表-通过id查询")
    @ApiOperation(value = "货架表-通过id查询", notes = "货架表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        BasicShelf basicShelf = basicShelfService.getById(id);
        if (basicShelf == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(basicShelf);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param basicShelf
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BasicShelf basicShelf) {
        return super.exportXls(request, basicShelf, BasicShelf.class, "货架表");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, BasicShelf.class);
    }

}
